#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#define PATH "."
#define FILENAME "fifo"

class NamedFifo
{
public:
    NamedFifo(const std::string &path, const std::string &name)
        : _path(path), _name(name)
    {
        _filename = _path + "/" + _name;
        // 创建命名管道
        int n = mkfifo(_filename.c_str(), 0666);
        if (n < 0)
        {
            std::cerr << "mkfifo failed" << std::endl;
        }
        else
        {
            std::cout << "mkfifo success" << std::endl;
        }
    }
    ~NamedFifo()
    {
        // 回收命名管道
        int n = unlink(_filename.c_str());
        if (n < 0)
        {
            std::cerr << "remove fifo failed" << std::endl;
        }
        else
        {
            std::cout << "remove fifo success" << std::endl;
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _filename;
};

class Fileoper
{
public:
    Fileoper(const std::string &path, const std::string &name)
        : _path(path), _name(name), _fd(-1)
    {
        _filename = _path + "/" + _name;
    }

    void OpenForRead()
    {
        _fd = open(_filename.c_str(), O_RDONLY);
        if(_fd < 0)
        {
            std::cerr << "open fifo failed" << std::endl;
        }
        else
        {
            std::cout << "open fifo success" << std::endl;
        }
    }

    void OpenForWrite()
    {
        _fd = open(_filename.c_str(), O_WRONLY);
        if(_fd < 0)
        {
            std::cerr << "open fifo failed" << std::endl;
        }
        else
        {
            std::cout << "open fifo success" << std::endl;
        }
    }

    void Write()
    {
        std::string message;
        while(true)
        {
            std::cout << "Please Enter#";
            std::getline(std::cin, message);
            write(_fd, message.c_str(), message.size());
        }
    }

    void Read()
    {
        while(true)
        {
            char buffer[1024];
            ssize_t n = read(_fd, buffer, sizeof(buffer)-1);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout << "Client say#" << buffer << std::endl;
            }
            else if(n == 0)
            {
                std::cout << "Client quit! me too!" << std::endl;
                break;
            }
            else
            {
                std::cerr << "read error" << std::endl;
                break;
            }
        }
    }

    void Close()
    {
        close(_fd);
    }
    
    ~Fileoper() {}

private:
    std::string _path;
    std::string _name;
    std::string _filename;
    int _fd;
};